<template>
  <div class="echarts" style="width: 100%; height: 500px;">
    <div style="width:100%;height:100%" ref="sctterMap"></div>
    <div class="mapChoose">
      <span v - for="(item, index) in parentInfo" :key="item.code">
        <span class="title" @click="chooseArea(item, index)">{{
            item.cityName == '全国'? '中国' : item.cityName
          }}</span>
        <span class="icon" v - show="index + 1 != parentInfo.length">></span>
      </span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import echarts from "echarts";
import { getNumberByArea } from '../../api/commonApi.js';
import useResize from '../../HCEcharts/mixins/useResize.js';

// 定义响应式数据
const myCharts = ref(null);
const geoJson = ref({ features: [] });
const parentInfo = ref([{ cityName: "全国", code: 100000 }]);
const crmPersonData = ref([]);
const mapData = ref([]);

// 获取地理JSON数据
const getGeoJson = (adcode) => {
    return new Promise((resolve, reject) => {
        // @ts - ignore
        AMapUI.loadUI(["geo/DistrictExplorer"], (DistrictExplorer) => {
            var districtExplorer = new DistrictExplorer();
            districtExplorer.loadAreaNode(adcode, function (error, areaNode) {
                if (error) {
                    console.error(error);
                    reject(error);
                    return;
                }
                let Json = areaNode.getSubFeatures();
                if (Json.length > 0) {
                    geoJson.value.features = Json;
                }
                else if (Json.length === 0) {
                    geoJson.value.features = geoJson.value.features.filter(
                        item => item.properties.adcode == adcode
                    );
                    if (geoJson.value.features.length === 0) {
                        reject(new Error('No features found'));
                        return;
                    }
                }
                resolve();
            });
        });
    });
};

// 获取crm各省客户数量
const getCrmPersonData = async () => {
    try {
        const res = await getNumberByArea();
        crmPersonData.value = res.data || [];
    } catch (error) {
        console.error('Error fetching crmPersonData:', error);
    }
};

// 获取地图数据
const getMapData = () => {
    const mapDataArray = geoJson.value.features.map((item) => {
        const numData = crmPersonData.value.find((v) => v.name === item.properties.name);
        return {
            name: item.properties.name,
            value: numData? numData.num : 0,
            cityCode: item.properties.adcode,
            children: numData && numData.children? numData.children : []
        };
    });
    const sortedMapData = mapDataArray.sort((a, b) => b.value - a.value);
    mapData.value = sortedMapData;
    initEcharts(sortedMapData);
};

// 渲染地图
const initEcharts = (mapData) => {
    const min = mapData[mapData.length - 1].value;
    const max = mapData[0].value;
    if (mapData.length === 1) {
        min = 0;
    }
    const geoCoordMap = {};
    const toolTipData = [];
    const mapFeatures = geoJson.value.features;
    const data = mapData;

    data.forEach((item) => {
        const name = item.name;
        toolTipData.push({
            name: name,
            value: [{ name: "客户数量", value: item.value + '人' }]
        });
    });

    mapFeatures.forEach((item) => {
        // 地区名称
        const name = item.properties.name;
        // 地区经纬度
        geoCoordMap[name] = item.properties.centroid || item.properties.center;
    });

    const convertData = (data) => {
        const res = [];
        for (let i = 0; i < data.length; i++) {
            const geoCoord = geoCoordMap[data[i].name];
            if (geoCoord) {
                res.push({
                    name: data[i].name,
                    value: geoCoord.concat(data[i].value)
                });
            }
        }
        return res;
    };

    myCharts.value = echarts.init(getCurrentInstance().$refs.sctterMap);
    echarts.registerMap("Map", geoJson.value);
    myCharts.value.setOption({
        tooltip: {
            trigger: "item",
            formatter: function (params) {
                if (typeof (params.value)[2] == "undefined") {
                    var toolTiphtml = '';
                    for (var i = 0; i < toolTipData.length; i++) {
                        if (params.name == toolTipData[i].name) {
                            toolTiphtml += toolTipData[i].name + ':<br>';
                            for (var j = 0; j < toolTipData[i].value.length; j++) {
                                toolTiphtml += toolTipData[i].value[j].name + ':' + toolTipData[i].value[j].value + '<br>';
                            }
                        }
                    }
                    return toolTiphtml;
                }
                else {
                    var toolTiphtml = '';
                    for (var i = 0; i < toolTipData.length; i++) {
                        if (params.name == toolTipData[i].name) {
                            toolTiphtml += toolTipData[i].name + ':<br>';
                            for (var j = 0; j < toolTipData[i].value.length; j++) {
                                toolTiphtml += toolTipData[i].value[j].name + ":" + toolTipData[i].value[j].value + '<br>';
                            }
                        }
                    }
                    return toolTiphtml;
                }
            }
        },
        visualMap: {
            min: min,
            max: max,
            left: "3%",
            bottom: "5%",
            calculable: true,
            seriesIndex: [1],
            inRange: {
                color: ["#B3F0FF", "#B3F0FF", "#5ADEFF"]
            },
            textStyle: {
                color: "#B3F0FF"
            }
        },
        geo: {
            show: true,
            map: 'Map',
            roam: true,
            zoom: 1.2,
            itemStyle: {
                normal: {
                    areaColor: "#B3F0FF",
                    borderColor: "#53D9FF",
                    borderWidth: 1.3
                },
                emphasis: {
                    areaColor: "#8dd7fc",
                    borderWidth: 1.6
                }
            },
            label: {
                normal: {
                    show: false,
                    fontSize: 0
                },
                emphasis: {
                    show: false
                }
            }
        },
        series: [
            {
                name: "散点",
                type:'scatter',
                data: convertData(data),
                coordinateSystem: 'geo',
                symbolSize: (val) => val[2] / 6,
                label: {
                    show: false,
                    normal: {
                        formatter: '{b}',
                        position: 'right',
                        show: false
                    },
                    emphasis: {
                        show: false
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#FEC03D'
                    }
                }
            },
            {
                type:'map',
                map: 'Map',
                geoIndex: 0,
                aspectScale: 0.75,
                showLegendSymbol: false,
                label: {
                    normal: {
                        show: true
                    },
                    emphasis: {
                        show: false,
                        textStyle: {
                            color: '#101010'
                        }
                    }
                },
                roam: true,
                itemStyle: {
                    normal: {
                        areaColor: '#031525',
                        borderColor: '#3B5077'
                    },
                    emphasis: {
                        areaColor: '#2B91B7'
                    }
                },
                animation: false,
                data: data
            },
            {
                name: '点',
                type:'scatter',
                coordinateSystem: 'geo',
                symbol: 'pin',
                symbolSize: (val) => {
                    const max = 480, min = 9;
                    const maxSize4Pin = 50, minSize4Pin = 20;
                    const a = (maxSize4Pin - minSize4Pin) / (max - min);
                    const b = minSize4Pin - a * min;
                    return a * val[2] + b;
                },
                label: {
                    normal: {
                        show: true,
                        formatter: (p) => {
                            switch (p.name) {
                                case "内蒙古自治区":
                                    p.name = "内蒙古";
                                    break;
                                case "西藏自治区":
                                    p.name = "西藏";
                                    break;
                                case "新疆维吾尔自治区":
                                    p.name = "新疆";
                                    break;
                                case "宁夏回族自治区":
                                    p.name = "宁夏";
                                    break;
                                case "广西壮族自治区":
                                    p.name = "广西";
                                    break;
                                case "香港特别行政区":
                                    p.name = "香港";
                                    break;
                                case "澳门特别行政区":
                                    p.name = "澳门";
                                    break;
                                default:
                                    break;
                            }
                            if (p.value[2] == 0) {
                                return '{name|' + p.name + '}';
                            }
                            else {
                                return '{num|' + p.value[2].toFixed() + '}';
                            }
                        },
                        textStyle: {
                            fontSize: 9,
                            rich: {
                                name: {
                                    color: '#fff'
                                },
                                num: {
                                    color: '#000'
                                }
                            }
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        color: 'rgba(255,255,0,0)'
                    }
                },
                zlevel: 6,
                data: convertData(data),
                layoutCenter: ['50%', '50%'],
                layoutSize: 430
            },
            {
                name: 'Top 5',
                type: 'effectScatter',
                coordinateSystem: 'geo',
                data: convertData(data.sort((a, b) => b.value - a.value).slice(0, 5)),
                symbolSize: (val) => val[2] / 3,
                showEffectOn:'render',
                rippleEffect: {
                    brushType:'stroke'
                },
                hoverAnimation: true,
                label: {
                    normal: {
                        formatter: '{b}',
                        position: 'center',
                        show: true,
                        textStyle: {
                            color: '#101010',
                            fontSize: 9
                        }
                    }
                },
                itemStyle: {
                    normal: {
                        color: 'rgba(255,255,0,0.8)',
                        shadowBlur: 10,
                        shadowColor: '#05C3F9'
                    }
                },
                zlevel: 1
            }
        ]
    }, true);

    const that = getCurrentInstance();
    myCharts.value.off("click");
    myCharts.value.on("click", (params) => {
        if (
            that.proxy.parentInfo[that.proxy.parentInfo.length - 1].code ==
            params.data.cityCode
        ) {
            return;
        }
        let data = params.data;
        if (params.data.children && params.data.children.length > 0) {
            that.proxy.crmPersonData = params.data.children;
        }
        that.proxy.parentInfo.push({
            cityName: data.name,
            code: data.cityCode
        });
        getGeoJson(data.cityCode).then(() => getMapData());
    });
};

// 选择切换市县
const chooseArea = (P_Val, P_Index) => {
    if (parentInfo.value.length === P_Index + 1) {
        return;
    }
    parentInfo.value.splice(P_Index + 1);
    getGeoJson(parentInfo.value[parentInfo.value.length - 1].code).then(() => getMapData());
};

onMounted(async () => {
    await getCrmPersonData();
    await getGeoJson(100000).then(() => getMapData());
    useResize();
});
</script>

<style lang="scss" scoped>
.echarts {
  position: relative;
  /* background: url("../assets/bg1.jpg") no - repeat;
  background - size: 100% 100%; */
}

.mapChoose {
  position: absolute;
  left: 20px;
  top: 10px;
  color: rgb(64, 158, 255);

 .title {
    padding: 5px;
    cursor: pointer;
  }

 .icon {
    font-family: "simsun";
    font-size: 25px;
    margin: 0 11px;
  }
}
</style>